<?php

namespace app\api\model;

class UserToken extends \app\admin\model\model\system\UserToken
{
    /**
     * 刷新token并返回
     * @param $userId
     * @param $username
     * @param $platform
     * @return string
     */
    public static function flush($userId, $username = '')
    {
        $token = self::createToken();
        $line = self::getLineByPkCommon($userId);
        if (!$line) {
            $res = self::addCommon([
                'token' => $token,
                'user_id' => $userId,
                'username' => $username,
            ]);
        } else {
            $data = [
                'token' => $token,
            ];
            $where = [
                'user_id' => $userId,
            ];
            $res = self::updateCommon($data, $where);
        }
        if (!$res) {
            \Debug::setDebug('token生成失败');
            return false;
        }
        return $token;
    }

    public static function getUserIdByToken($token)
    {
        $where = [
            'token' => $token,
        ];
        return self::getValueCommon($where, 'user_id');
    }

    public static function getTokenByUserId($userId)
    {
        $where = [
            'user_id' => $userId,
        ];
        return self::getValueCommon($where, 'token');
    }

    /**
     * 生成token
     * @return string
     */
    public static function createToken()
    {
        return md5(uniqid(mt_rand(), true));
    }
}